<template>
<div>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
     v-dialogDrag
    :visible.sync="visible">
    <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="method==='view'"
             label-width="120px">
      <el-row  :gutter="15">
        <el-col :span="12">
            <el-form-item label="父级名称" prop="parent.name"
                :rules="[
                 ]" >
              <el-input v-model="inputForm.parent.name" placeholder="父级编号" disabled @getValue="(value) => {inputForm.parent.id=value}"   ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="设备层级" prop="level"
                :rules="[
                 ]">
                 <el-select v-model="inputForm.level" placeholder="请选择" disabled clearable style="width: 100%;">
                           <el-option
                             v-for="item in $dictUtils.getDictList('basicdata_part_device_node_hierarchy')"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value">
                           </el-option>
                  </el-select>
           </el-form-item>
        </el-col>
        <el-col :span="12" v-if="inputForm.level ==='3'">
            <el-form-item label="设备级别" prop="grade"
                :rules="[
                  {required: true, message:'设备级别不能为空', trigger:'blur'}
                 ]">
                    <el-radio-group v-model="inputForm.grade" size="small">
                        <el-radio-button v-for="item in $dictUtils.getDictList('basicdata_part_device_node_grade')" :label="item.value" :key="item.id">{{item.label}}</el-radio-button>
                    </el-radio-group>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="设备编码" prop="code"
                :rules="[
                 ]" ref="aa">
              <el-input v-model="inputForm.code" placeholder="请填写设备编码"  ref="input"  ></el-input>
              <!-- <span v-if="true" style="color: red;" :v-model="inputForm.sort">this.inputForm.sort</span> -->
              <span v-if="isPartDeviceNodeCodeBoolean" style="color: #f56c6c; font-size: 12px;"> 设备编码{{this.inputForm.code}}已存在 </span>
              <span v-if="isCodeLength" style="color: #f56c6c; font-size: 12px;">请填入规定长度为{{this.codeLength}}设备编码 </span>
           </el-form-item>
        </el-col>
        <el-col :span="12" v-if="inputForm.level !== '5'">
            <el-form-item label="设备名称" prop="name"
                :rules="[{required: true, message:'设备名称不能为空', trigger:'blur'}]">
              <el-input v-model="inputForm.name" placeholder="请填写设备名称" ></el-input>
           </el-form-item>
        </el-col>
        <!-- <el-col :span="12" v-show= false>
            <el-form-item label="物料名称" prop="name"
                :rules="[
                 ]">
              <el-input v-model="inputForm.name" placeholder="请填写物料名称" ></el-input>
           </el-form-item>
        </el-col> -->
        <el-col :span="12">
            <el-form-item label="运行状态" prop="runState"
                :rules="[
                 ]">
                <el-switch
                  v-model="inputForm.runState"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="运行"
                  active-value="1"
                  inactive-value="0"
                  inactive-text="停机"
                  >
                </el-switch>
           </el-form-item>
        </el-col>
        <el-col :span="12" v-if="inputForm.level == '5'">
            <el-form-item label="类别" prop="type"
                :rules="[
                 ]">
                <el-select v-model="inputForm.type" placeholder="请选择" clearable style="width: 100%;">
                          <el-option
                            v-for="item in $dictUtils.getDictList('basicdata_part_device_node_category')"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                      </el-select>
           </el-form-item>
        </el-col>
        <el-col :span="12" v-if="inputForm.level == '5'">
            <el-form-item label="用途" prop="purpose"
                :rules="[
                 ]">
                <el-select v-model="inputForm.purpose" placeholder="请选择" clearable style="width: 100%;">
                          <el-option
                            v-for="item in $dictUtils.getDictList('basicdata_part_device_node_purpose')"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                      </el-select>
           </el-form-item>
        </el-col>
        <el-col :span="12" v-if="inputForm.purpose === 'repair' && inputForm.level =='5'">
            <el-form-item label="使用周期" prop="lifeCycle"
                :rules="[
                   {validator: validator.isNumber, trigger:'blur'},
                   {required: true, message:'使用周期不能为空', trigger:'blur'},

                 ]">
              <el-input v-model="inputForm.lifeCycle" placeholder="请填写使用周期"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12" v-if="inputForm.purpose !== 'repair' && inputForm.level ==='5' && inputForm.purpose !== ''">
            <el-form-item label="消耗定额" prop="comsumeQuota"
                :rules="[
                  {required: true, message:'消耗定额不能为空', trigger:'blur'},
                 ]">
              <el-input v-model="inputForm.comsumeQuota" placeholder="请填写消耗定额"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12" v-if="inputForm.level == '5' || inputForm.level == '4'">
            <el-form-item label="责任人" prop="duty.id"
                :rules="[
                 ]">
                <user-select :limit='1' :value="inputForm.duty.id" @getValue='(value) => {inputForm.duty.id=value}'></user-select>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="是否显示" prop="isShow"
                :rules="[
                 ]">
                    <el-radio-group v-model="inputForm.isShow">
                        <el-radio v-for="item in $dictUtils.getDictList('yes_no')" :label="item.value" :key="item.id">{{item.label}}</el-radio>
                    </el-radio-group>
           </el-form-item>
        </el-col>
        <el-col :span="12" v-if="inputForm.level == '3'">
            <el-form-item label="是否是物联设备" prop="isIot"
                :rules="[
                 ]">
                    <el-radio-group v-model="inputForm.isIot">
                        <el-radio v-for="item in $dictUtils.getDictList('yes_no')" :label="item.value" :key="item.id">{{item.label}}</el-radio>
                    </el-radio-group>
           </el-form-item>
        </el-col>
        <el-col :span="12" v-if= false>
            <el-form-item label="排序" prop="sort"
                :rules="[
                  {required: true, message:'排序不能为空', trigger:'blur'},
                  {validator: validator.isNumber, trigger:'blur'}
                 ]">
              <el-input-number v-model="inputForm.sort" placeholder="请填写排序" :step="10"     ></el-input-number>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="备注信息" prop="remarks"
                :rules="[
                 ]">
          <el-input type="textarea" v-model="inputForm.remarks" placeholder="请填写备注信息"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="24" v-if="inputForm.level == '5'">
            <el-form-item label="物料编码" prop="erpMaterialId"
                :rules="[
                 ]">
              <material-code :limit='1' :value="inputForm.erpMaterialId" @getValue='(value) => {inputForm.erpMaterialId=value}'></material-code>
           </el-form-item>
        </el-col>
        </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" v-if="method != 'view'" @click="doSubmit()" v-noMoreClick>确定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import UserSelect from '@/components/userSelect'
  import materialCode from '@/myComponents/materialCode/index.vue'
  export default {
    props: {
      row: ''
    },
    data () {
      return {
        title: '',
        method: '',
        visible: false,
        loading: false,
        booleanCode: true,
        booleanName: '',
        inputForm: {
          id: '',
          parent: {
            id: '',
            name: ''
          },
          code: '',
          name: '',
          level: '',
          sort: 0,
          erpMaterialId: '',
          type: '',
          purpose: '',
          lifeCycle: '',
          comsumeQuota: '',
          duty: {
            id: ''
          },
          runState: '1',
          isShow: '1',
          isLeaf: '1',
          grade: '',
          isIot: '',
          remarks: ''
        },
        code1: '', //临时存放code值
        isdata: true,
        PartDeviceNodeCodeName: '', // 请求到的五级部件编码名字
        isPartDeviceNodeCodeBoolean: false, // 请求到的五级部件编码是否重复
        isCodeLength: false, // 判断编码长度
        codeLength: '', // 编码长度
        isadd: '',
        // ischange: '0',//修改时设备编码值是否改变
        methods: '' // 用于解决发送请求时候确定能点问题（用于转换）
      }
    },
    components: {
      SelectTree,
      UserSelect,
      materialCode
    },
    watch: {
      'inputForm.erpMaterialId': {
        // watch用时要慎重。。。
       handler (newVal, oldVal) {
          if (this.inputForm.level === '5') {
            this.$http({
                url: `/spareparts/material/sparepartsMaterialCodeData/queryById?id=${newVal}`,
                method: 'get'
              }).then(({data}) => {
              this.inputForm.name = data.sparepartsMaterialCodeData.sparepartsName
              let ABC = data.sparepartsMaterialCodeData.sparepartsABCCategory
              // if (data.sparepartsMaterialCodeData.sparepartsABCCategory === undefined) {
              //   ABC = C
              // }
              if (this.method === 'addChild' && this.inputForm.level === '5' && data.sparepartsMaterialCodeData.sparepartsABCCategory !== undefined) {
                this.$http({
                  url: `/basicdata/basictree/partDeviceNode/queryCodeReturn?code=${this.inputForm.code.substring(0, 12) + ABC}&level=${this.inputForm.level}`,
                  method: 'get'
                }).then(({data}) => {
                  if (data.code) {
                    this.inputForm.code = data.code
                  } else {
                    this.inputForm.code = this.inputForm.code.substring(0, 12) + ABC + '001' //如果值为空则变为001
                  }
                })
              }
            })
          }
         },
          immediate: true // 第一次绑定数据时就触发
      },
      'inputForm.code': function (newVal, oldVal) {
        if (this.inputForm.level === '1') {
          if (newVal.length !== 2) {
            this.isCodeLength = true
            this.codeLength = 2
          } else {
            this.isCodeLength = false
          }
        } else if (this.inputForm.level === '2') {
          if (newVal.length !== 5) {
            this.isCodeLength = true
            this.codeLength = 5
          } else {
            this.isCodeLength = false
          }
        } else if (this.inputForm.level === '3') {
          if (newVal.length !== 9) {
            this.isCodeLength = true
            this.codeLength = 9
          } else {
            this.isCodeLength = false
          }
        } else if (this.inputForm.level === '4') {
          if (newVal.length !== 12) {
            this.isCodeLength = true
            this.codeLength = 12
          } else {
            this.isCodeLength = false
          }
        } else if (this.inputForm.level === '5') {
          if (newVal.length !== 16) {
            this.isCodeLength = true
            this.codeLength = 16
          } else {
            this.isCodeLength = false
          }
        }
        // if (newVal.length !== 2 && newVal.length !== 5 && newVal.length !== 9 && newVal.length !== 12) {
        //   this.isCodeLength = true
        // } else {
        //   this.isCodeLength = false
        // }
       },
       //根据grade值在新建第三层中设备编码内添加ABCD
      'inputForm.grade' (value1, value2) {
        if (this.method === 'edit') {
          console.log(value1)
          this.code1 = this.inputForm.code.substring(0, 5)
            if (value1 !== value2 && (value2 !== undefined || value2 !== '' || value2 !== null)) {
              this.ischange = '1'
            }
            if (value1 === '1') {
              this.inputForm.code = this.code1 + 'A'
            }
            if (value1 === '2') {
              this.inputForm.code = this.code1 + 'B'
            }
            if (value1 === '3') {
              this.inputForm.code = this.code1 + 'C'
            }
            if (value1 === '4') {
              this.inputForm.code = this.code1 + 'D'
            }
          // this.inputForm.code = this.code1
        }
        if (value1 === '1' && this.method === 'addChild') {
          this.inputForm.code = this.code1 + 'A'
        }
        if (value1 === '2' && this.method === 'addChild') {
          this.inputForm.code = this.code1 + 'B'
        }
        if (value1 === '3' && this.method === 'addChild') {
          this.inputForm.code = this.code1 + 'C'
        }
        if (value1 === '4' && this.method === 'addChild') {
          this.inputForm.code = this.code1 + 'D'
        }
        if ((this.method === 'addChild' || this.method === 'edit') && this.inputForm.level === '3') {
          this.methods = this.method
          this.method = 'view'
          this.$http({
            url: `/basicdata/basictree/partDeviceNode/queryCodeReturn?code=${this.inputForm.code}&level=${this.inputForm.level}`,
            method: 'get'
          }).then(({data}) => {
            if (data.code) {
              this.inputForm.code = data.code
            } else {
              this.inputForm.code = this.inputForm.code + '001' //如果值为空则变为001
            }
          })
          this.method = this.methods
        }
      }
    },
    methods: {
      // 重置设备名称，类别，用途，层级
      reset: function () {
        this.inputForm.remarks = ''
        this.inputForm.name = ''
        this.inputForm.purpose = ''
        this.inputForm.type = ''
        this.inputForm.grade = ''
        this.isCodeLength = false
        this.isPartDeviceNodeCodeBoolean = false
      },
      init (method, obj) {
        this.method = method
        if (method === 'add') {
          this.title = '添加根设备节点'
        } else if (method === 'addChild') {
          this.title = '添加下级设备节点'
        } else if (method === 'edit') {
          this.title = '修改设备节点'
        } else if (method === 'view') {
          this.title = '查看设备节点'
        }
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          if (method === 'add') {
            this.inputForm.id = ''
            this.inputForm.parent.id = 0
            this.inputForm.code = obj.parent.code
            this.inputForm.level = '1' //新建时 设备层级恒为1
            this.reset()
            this.$http({
              url: `/basicdata/basictree/partDeviceNode/queryCodeReturn?code=${''}&level=${this.inputForm.level}`,
              method: 'get'
            }).then(({data}) => {
              if (data.code) {
                this.inputForm.code = data.code
              } else {
                this.inputForm.code = '01' //如果值为空则变为001
              }
            })
          } else if (method === 'addChild') {
            this.inputForm.id = ''
            this.inputForm.parent.name = '[' + obj.parent.code + ']' + obj.parent.name
            this.inputForm.parent.id = obj.parent.id
            this.inputForm.level = obj.parent.level - 0 + 1 + '' //添加下级节点时设备层级加一
            this.inputForm.code = obj.parent.code
            this.code1 = obj.parent.code
            if (this.inputForm.level === '3') {
              this.inputForm.isIot = '1'
            }
            this.reset()
            if (this.inputForm.level !== '3' && this.inputForm.level !== '5') {
              this.$http({
                url: `/basicdata/basictree/partDeviceNode/queryCodeReturn?code=${this.inputForm.code}&level=${this.inputForm.level}`,
                method: 'get'
              }).then(({data}) => {
                if (data.code) {
                  this.inputForm.code = data.code
                } else {
                  this.inputForm.code = this.inputForm.code + '001' //如果值为空则变为001
                }
              })
            }
          } else if (method === 'edit' || method === 'view') {
            this.inputForm.id = obj.id
            // 修改或者查看
            this.loading = true
            this.$http({
              url: `/basicdata/basictree/partDeviceNode/queryById?id=${this.inputForm.id}`,
              method: 'get'
            }).then(({data}) => {
              this.inputForm = this.recover(this.inputForm, data.partDeviceNode)
              this.loading = false
            })
          }
        })
      },
      feedBack (data) {
        this.row.name = data.name
        this.row.runState = data.runState
        this.row.isShow = data.isShow
        this.row.level = data.level
        this.row.comments = data.comments
        this.row.grade = data.grade
        this.row.isIot = data.isIot
      },
      // 表单提交
      doSubmit () {
        this.$http({
          url: `/basicdata/basictree/partDeviceNode/queryCode?code=${this.inputForm.code}`,
          method: 'get'
        }).then(({data}) => {
          if ((data.PartDeviceNodeCode.booleanCode || this.isCodeLength === true) && this.inputForm.name !== '') {
            this.isPartDeviceNodeCodeBoolean = data.PartDeviceNodeCode.booleanCode
            this.PartDeviceNodeCodeName = data.PartDeviceNodeCode.name
            if (this.method !== 'addChild') {
              this.isPartDeviceNodeCodeBoolean = false
              this.$refs['inputForm'].validate((valid) => {
                if (valid) {
                  this.loading = true
                  this.$http({
                    url: `/basicdata/basictree/partDeviceNode/save`,
                    method: 'post',
                    data: this.inputForm
                  }).then(({data}) => {
                    if (data && data.success) {
                      this.visible = false
                      this.$message.success(data.msg)
                      if (this.method === 'edit') {
                        this.feedBack(this.inputForm) // 更新当行数据，进行回显
                      }
                      if (this.method === 'add') { // 添加根节点，刷新整个列表
                        this.$emit('refreshDataList')
                      }
                      if (this.method === 'addChild') {
                        // this.$emit('refreshParent')
                      }
                    }
                    this.loading = false
                  })
                }
              })
            }
          } else {
            this.isPartDeviceNodeCodeBoolean = false
            this.$refs['inputForm'].validate((valid) => {
              if (valid) {
                this.loading = true
                this.$http({
                  url: `/basicdata/basictree/partDeviceNode/save`,
                  method: 'post',
                  data: this.inputForm
                }).then(({data}) => {
                  if (data && data.success) {
                    this.visible = false
                    this.$message.success(data.msg)
                    if (this.method === 'edit') {
                      this.feedBack(this.inputForm) // 更新当行数据，进行回显
                    }
                    if (this.method === 'add') { // 添加根节点，刷新整个列表
                      this.$emit('refreshDataList')
                    }
                    if (this.method === 'addChild') {
                      // this.$emit('refreshParent')
                    }
                  }
                  this.loading = false
                })
              }
            })
          }
        })
      }
    }
  }
</script>
